/* eslint-disable no-unused-vars */
import extend from "lodash/extend";
import isFunction from "lodash/isFunction";

const ATTR_MAPPING_COMPONENT = {
  width: {
    comp: "el-input-number",
    label: "宽度"
  },
  height: {
    comp: "el-input-number",
    label: "高度"
  },
  x: {
    comp: "el-input-number",
    compProps: {},
    label: "X"
  },
  diameter: {
    comp: "el-input-number",
    compProps: {},
    label: "直径"
  },
  y: {
    comp: "el-input-number",
    label: "Y"
  },
  rotate: {
    comp: "el-input-number",
    label: "角度"
  },
  strokeWidth: {
    comp: "el-input-number",
    compProps: { min: 1, max: 5 },
    label: "边框宽度"
  },
  stroke: {
    comp: "el-color-picker",
    label: "边框色"
  },
  bgColor: {
    comp: "el-color-picker",
    label: "背景色"
  }
};

export default {
  props: {
    figure: {
      type: Object,
      default: () => ({})
      // required: true
    }
  },
  data() {
    return {
      figureAttrs: {},
      setter: {},
      getter: {}
    };
  },
  watch: {
    figure: function () {
      if (this.figure) {
        this.setter = extend({}, this.figure.setterWhitelist);
        this.getter = extend({}, this.figure.getterWhitelist);
        this.calcFigureAttr();
        this.figure.on("attr", () => this.calcFigureAttr());
      } else {
        this.figure.off("attr");
        this.figureAttrs = {};
        this.setter = {};
        this.getter = {};
      }
    }
  },
  render(h) {
    return h(
      "el-form",
      {
        props: {
          "label-width": "80px"
        }
      },
      this.renderItem(h)
    );
  },
  methods: {
    calcFigureAttr() {
      Object.keys(this.figure.getterWhitelist).forEach(key => {
        let fn = this.getter[key];
        if (isFunction(fn)) {
          this.$set(this.figureAttrs, key, fn.call(this.figure));
        }
      });
    },

    renderItem(h) {
      let result = [];
      Object.keys(this.figureAttrs).map(attr => {
        let mapping = ATTR_MAPPING_COMPONENT[attr];
        if (mapping) {
          let value = this.figureAttrs[attr];
          let setter = this.setter[attr];

          let { label, comp, compProps } = mapping;
          result.push(
            h("el-form-item", { props: { label } }, [
              h(comp, {
                props: {
                  value,
                  ...compProps
                },
                on: {
                  input: v => {
                    this.figureAttrs[attr] = v;
                    isFunction(setter) && setter.call(this.figure, v);
                  }
                }
              })
            ])
          );
        }
      });

      return result;
    }
  }
};
